//压缩图片

//base64转file， 仅使用Chrome和Firefox
function dataURLtoFile(dataurl, filename) {//将base64转换为文件
  var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], `img/${mime.split('/')[1]}`, {type: mime})
}

//利用canvas 压缩生成base64
let canvasDataURL = str => new Promise(resolve => {
  let img = new Image();
  img.src = str;
  img.onload = function () {
    //默认按照比例压缩
    let scale = this.width / this.height;
    //规定压缩后的大小
    let canvasWidth = 600;
    let canvasHeight = canvasWidth / scale;
    //生成canvas
    let canvas = document.createElement('canvas');
    let ctx = canvas.getContext('2d');
    //创建节点属性
    canvas.width = canvasWidth;
    canvas.height = canvasHeight;
    let anw = document.createAttribute('width');
    anw.nodeValue = canvasWidth;
    let anh = document.createAttribute('height');
    anh.nodeValue = canvasHeight;
    canvas.setAttributeNode(anw);
    canvas.setAttributeNode(anh);
    ctx.drawImage(this, 0, 0, canvasWidth, canvasHeight);
    //图像质量,值越小，所绘制出的图像越模糊
    let quality = 0.9;
    let base64String = canvas.toDataURL('img/png', quality);
    let getFile = dataURLtoFile(base64String);
    resolve({
      getFile : getFile ,
      base64String : base64String
    });
  }
});
let fileToBase64 = file => new Promise( resolve => {
  let base64;
  let reader = new FileReader();
  reader.onload = function (e) {
    base64 = e.target.result;
    canvasDataURL(base64).then(res => {
      resolve({getFile : res.getFile ,  base64String : res.base64String });
    })
  };
  reader.readAsDataURL(file);
});
export function compressImg(file) {
  return new Promise( async (resolve , reject) => {
    let maxSize = 1024 * 1024 * 2; //最大不超过2M
    let count = 0;
    if(File && file.size > maxSize){
      let compressOver = false;
      while ( count < 30 && !compressOver){
        count++;
        console.log('压缩图片次数++++'+count);
        let result = await fileToBase64(file);
        let getFile = result.getFile;
        let size = getFile.size;
        if(size > maxSize) {
          result = await fileToBase64(getFile);
        } else {
          compressOver = true;
          resolve({
            base64Img : result.base64String ,
            inputFile : result.getFile,
            count : count,
          });
        }
      }
    }
    else {
      //浏览器不支持file压缩
      let result = await fileToBase64(file);
      resolve({
        base64Img : result.base64String || '',
        inputFile : file,
        count :count,
      });
    }
  })
}
